<?php

namespace app\community\controller\user_list;

use app\admin\service\UserService;
use app\BaseController;
use app\model\DepartmentAdminModel;
use app\model\RatingScaleModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskModel;
use app\model\TaskUserModel;
use app\model\UnitModel;
use app\model\UserModel;
use think\App;

class UserList extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new UserModel();
    }

    /**
     * 普通用户列表
     * @return false|string
     */
    public function userList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'community_address|社区地址' => 'require'
            ]);
            $where = [];
            if (!empty($param['status'])) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            if (isset($param['student_status']) && strlen($param['student_status']) > 0) {
                $where[] = ['student_status', '=', $param['student_status']];
            }
            if (isset($param['department_id']) && strlen($param['department_id']) > 0) {
                $where[] = ['department_id', '=', $param['department_id']];
            }
            if (!empty($param['department_admin_id'])) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $department_ids = $DepartmentAdminModel->where('uid', '=', $param['department_admin_id'])->column('department_id');
                if (count($department_ids) > 0) {
                    $where[] = ['department_id', 'in', $department_ids];
                } else {
                    $where[] = ['department_id', '=', '-1'];
                }
            }
            if (!empty($param['id'])){
                $where[] = ['id', 'in', $param['id']];
            }
            $where[] = ['role_mode', '=', 3];
            $where[] = ['company_id', '=', $this->userData['company_id']];
            $where[] = ['areas_id', '=', $this->userData['areas_id']];
            $where[] = ['community_address', '=', $param['community_address']];
            $query = $this->mode->where($where);
            $data = $query->paginate($param['pageSize'])->toArray();
            if (count($data['data']) > 0) {
                $UserService = new UserService($this->app);
                $DepartmentAffiliationAll = $UserService->getDepartmentAffiliationAll($this->userData['unit_id']);
                $department_ids = array_column($data['data'], 'department_id');
                $DepartmentAdminAll = $UserService->getDepartmentAdminAll($department_ids);
                foreach ($data['data'] as &$item) {
                    //部门归属
                    $item['ascription_name'] = $DepartmentAffiliationAll[$item['department_id']]['ascription_name'] ?? '';
                    //所在部门
                    $item['department_name'] = $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '';
                    //部门number（班级编号）
                    $item['department_number'] = $DepartmentAffiliationAll[$item['department_id']]['number'] ?? '';
                    //部门管理员
                    $item['department_admin'] = $DepartmentAdminAll[$item['department_id']]['user_name'] ?? '';
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评报告
     * @return false|string
     */
    public function selfReport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'uid|用户ID' => 'require'
            ]);

            $where = [];
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['name'])) {
                $RatingScaleModel = new RatingScaleModel();
                $UserModel = new UserModel();
                $rating_scale_ids = $RatingScaleModel->where('name', 'like', '%' . $param['name'] . '%')->column('id');
                $uids = $UserModel->where('name', 'like', '%' . $param['name'] . '%')->column('id');
                if (count($rating_scale_ids) > 0 || count($uids) > 0) {
                    if (count($rating_scale_ids) > 0) {
                        $where[] = ['rating_scale_id', 'in', $rating_scale_ids];
                    }
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    }
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['type_id'])) {
                $RatingScaleModel = new RatingScaleModel();
                $rating_scale_ids = $RatingScaleModel->where('type_id', '=', $param['type_id'])->column('id');
                if (count($rating_scale_ids) > 0) {
                    $where[] = ['rating_scale_id', 'in', $rating_scale_ids];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
//            if (!empty($param['answer_role'])) {
//                $where[] = ['answer_role', '=', $param['answer_role']];
//            }
            if (!empty($param['is_explain'])) {
                $where[] = ['is_explain', '=', $param['is_explain']];
            }
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                $where[] = ['is_warning', '=', $param['is_warning']];
            }
            if (!empty($param['id'])) {
                if (is_array($param['id'])) {
                    $where[] = ['id', 'in', $param['id']];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['uid', '=', $param['uid']];
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $query = $SelfEvaluationResultModel->where($where);
            $data = $query->field('id,uid,rating_scale_id,answer_role,total_score,time,result_read_auth,is_warning,warning_id,is_explain,is_special_group,is_follow,is_interfere')
                ->with([
                    'user' => function ($query) {
                        $query->with(['departmentName', 'unitName']);
                    },
                    'ratingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    },
                    'RatingScaleFactorWarningModel'
                ])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            $departmentIds = array_column($data['data'], 'department_id');
            $DepartmentAdminModel = new DepartmentAdminModel();
            $departmentList = $DepartmentAdminModel->where('department_id', 'in', $departmentIds)->with(['userName'])->select()->toArray();
            $departmentData = [];
            foreach ($departmentList as $item) {
                $departmentData[$item['department_id']][] = $item['user_name'];
            }
            foreach ($data['data'] as &$item) {
                $item['department_admins'] = $departmentData[$item['department_id']] ?? [];
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告
     * @return false|string
     */
    public function taskReport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'user_id|用户ID' => 'require'
            ]);
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['start_time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['start_time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['start_time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', '=', $param['uid']];
            }
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                if ($param['is_warning'] == 1) {
                    $where[] = ['warning_num', '>', 0];
                } else {
                    $where[] = ['warning_num', '=', 0];
                }
            }
            /*根据用户ID查询区域内有关他的任务ID-开始*/
            $TaskUserModel = new TaskUserModel();
            $taskIds = $TaskUserModel->where('uid',$param['user_id'])->column('task_id');
            /*根据用户ID查询区域内有关他的任务ID-结束*/
            $where[] = ['id', 'in', $taskIds];
            $TaskModel = new TaskModel();
            $query = $TaskModel->where($where);
            $data = $query->field('id,uid,name,rating_scale_count,user_count,start_time,end_time,user_complete_num,result_read_auth,warning_num,user_complete_rate')
                ->with(['userName'])
                ->withCount(['AnswerRoleUser', 'AnswerRoleParent'])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告中间详情
     * @return bool|string
     */
    public function TaskEvaluationMiddleInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $TaskUserModel = new TaskUserModel();
            $data = $TaskUserModel->where([
                ['task_id', '=', $param['id']],
                ['uid', '=', $param['uid']]
            ])->with([
                'RatingScale' => function ($query) {
                    $query->with(['ratingScaleTypeName']);
                },
                'TaskUserResult'
            ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}